import React from 'react'
import './App.css'

// 函数式定义只能有 props,没有state
function Square (props) {
  let winnerSquares = ""
  if (props.winnerSquares.length > 0 && props.winnerSquares.includes(props.index)) {
    winnerSquares = "winnerSquares"
  }
  return (
    <button className={["square", winnerSquares].join(' ')}
      onClick={props.onClick}>
      {props.value}
    </button>
  )
}
// 继承类组件 可以使用 state 和 props
class Board extends React.Component {
  constructor(props) {
    super(props)
    this.state = {}
  }

  renderSquare (index) {
    return (
      <Square
        key={index}
        winnerSquares={this.props.winnerSquares}
        index={index}
        value={this.props.squares[index]}
        onClick={() => this.props.onClick(index)} />
    )
  }
  render () {
    let ret = []
    for (let i = 0; i < 3; i++) {
      let yT = []
      for (let y = 0; y < 3; y++) {
        yT.push(this.renderSquare(i * 3 + y))
      }
      ret.push(<div key={i} className="board-row">{yT}</div>)
    }
    return (
      <div>
        {ret}
      </div>
    )
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      history: [{
        squares: Array(9).fill(null),
        winnerSquares: []
      }],
      stepNumber: 0,
      xIsNext: true,
      reverse: false,
    }
  }

  getIsNextPlayer () {
    // debugger
    const winner = calculateWinner(this.state.history[this.state.stepNumber].squares)
    if (winner) {
      return (
        <div>胜利者是：{winner.square}</div>
      )
    }
    if (this.state.stepNumber === 9) {
      return <div>这一局谁都没有输，再接再厉！</div>
    }
    return (
      <div>下一步出：{this.state.xIsNext ? "X" : "O"}</div>
    )
  }

  onClickHandle (index) {
    // debugger
    const history = this.state.history.slice(0, this.state.stepNumber + 1)
    const squares = this.state.history[this.state.stepNumber].squares.slice()
    if (calculateWinner(squares) || squares[index]) {
      return
    }

    squares[index] = this.state.xIsNext ? "X" : "O"
    let winnerSquares = []
    const t = calculateWinner(squares)
    if (t) {
      winnerSquares = t.winnerSquares
    }
    this.setState({
      history: history.concat([{
        squares: squares,
        winnerSquares: winnerSquares
      }]),
      stepNumber: history.length,
      xIsNext: !this.state.xIsNext,
    })
  }

  turnTo (index) {
    this.setState({
      stepNumber: index,
      xIsNext: (index % 2) === 0
    })
  }
  getButtonList () {
    const moves = this.state.history.map((item, index) => {
      let desc = '游戏初始化'
      let currentXY = ''
      if (index > 0) {
        desc = "返回第" + index + "步"
        currentXY = this.getCurrentXY(item.squares, this.state.history[index - 1].squares)
      }
      return (
        <li key={index}>
          <button onClick={() => this.turnTo(index)}>
            {this.getCurrentB(desc, index, this.state.stepNumber)}</button> {currentXY}
        </li>
      )
    })

    return this.state.reverse ? moves.reverse() : moves
  }
  getCurrentB (item, index, currIndex) {
    if (index === currIndex) {
      return (
        <b>{item}</b>
      )
    } else {
      return item
    }
  }
  getCurrentXY (item1, item2) {
    let ret = null
    for (let index = 0; index < item1.length; index++) {
      if (item1[index] !== item2[index]) {
        ret = this.getXY(index)
      }
    }
    return ret
  }

  getXY (number) {
    switch (number) {
      case 0:
        return "{x:1, y:1}"
      case 1:
        return "{x:1, y:2}"
      case 2:
        return "{x:1, y:3}"
      case 3:
        return "{x:2, y:1}"
      case 4:
        return "{x:2, y:2}"
      case 5:
        return "{x:2, y:3}"
      case 6:
        return "{x:3, y:1}"
      case 7:
        return "{x:3, y:2}"
      case 8:
        return "{x:3, y:3}"
      default:
        return "{x:null, y:null}"
    }
  }

  sortByUpDown () {
    this.setState({
      reverse: !this.state.reverse
    })
  }

  render () {
    return (
      <div className="game">
        <div className="game-board">
          <Board
            winnerSquares={this.state.history[this.state.stepNumber].winnerSquares}
            squares={this.state.history[this.state.stepNumber].squares}
            onClick={index => this.onClickHandle(index)}
          />
        </div>
        <div className="game-info">
          <div>{this.getIsNextPlayer()} </div>
          <div><button onClick={() => this.sortByUpDown()}>排序按钮</button></div>
          <div>{this.getButtonList()}</div>
        </div>
      </div>

    )
  }
}

function calculateWinner (squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      // return squares[a];
      return {
        square: squares[a],
        winnerSquares: lines[i]
      }
    }
  }
  return null;
}

export default Game